import { PageModalService } from './../../shared/service/page-modal-service';
import { Component, OnInit , Input} from '@angular/core';
import { AlertController } from '@ionic/angular';
import { AppGlobalService } from './../../shared/service/app-global.service';
import { HttpService } from './../../shared/service/http.service';
declare let Wechat: any;
declare let cordova;
declare var wx;
declare var WeixinJSBridge;

@Component({
  selector: 'app-pay-way',
  templateUrl: './pay-way.component.html',
  styleUrls: ['./pay-way.component.scss'],
})
export class PayWayComponent implements OnInit {

  @Input() tagData: any;
  retry = 0;
  vlaue: any;
  client: any;
  payData: any;
  orderNumber: any;
  wxCode = 0;
  userAgent = window.navigator.userAgent.toLowerCase();
  isWXH5 = false;
  showWXPay = true; // 汇付 微信内置浏览器之外暂时不显示微信支付
  isHuifu = false;
  isWXMIN = false;
  miniprogramLoginCode = 0;
  constructor(
    private appGlobalService: AppGlobalService,
    private alert: AlertController,
    private http: HttpService,
    private pageModalService: PageModalService
  ) { }

   ngOnInit() {
    const that = this;
    if ((typeof wx) !== 'undefined') {
      wx.miniProgram.getEnv((r) => {
        if (r.miniprogram) {
          if (localStorage.getItem(localStorage.getItem('sessionId')) === "bindWeChatLoginCode" ) {
            if (localStorage.getItem('loginAccount') === "19925304828") {
              that.appGlobalService.showToast('已有绑定wxloginCode', 1500, "top");
            } else {
              console.log("已有绑定wxloginCode");
            }

          } else {
            // 发送到小程序 绑定
            const path = '/pages/session/session?sessionId=' + encodeURIComponent(localStorage.getItem('sessionId'));

            wx.miniProgram.navigateTo({ url: path });
          }
        }
      });
    }
    this.wxCode = this.appGlobalService.wxPayCode;
    if ( this.tagData.data.button.submit.params.huifu &&
         this.tagData.data.button.submit.params.huifu === 'true' ) {
        this.isHuifu = true;
    }
    // this.demoData()
    // 设置默认微信选中
    this.tagData.data.payWay.forEach((v) => {
      if ('1' === v.value) {
          v.checked = true;
          this.vlaue = v.value;
        } else {
        v.checked = false;
      }
    });
    this.client = localStorage.getItem('client');
    if (localStorage.getItem('client') === "JSAPI") {
      // 小程序
      this.client = "JSAPI";
      this.isWXMIN = true;
    } else {
      // 如果是微信内先请求code
      if (this.getWXH5Code()) {
        return;
      }
      // localStorage.setItem("client", 'BROWSER');
      // localStorage.setItem("client", 'JSAPI');
      if (this.userAgent.match(/micromessenger/i)) {
          this.client = "JSAPI";
          if (this.wxCode !== 0 && localStorage.getItem("autoPay") === "1") {
            localStorage.removeItem("autoPay");
            // 拿到code自动支付
            this.pay(this.tagData.data.button);
          }
      } else {
        if (this.client === "BROWSER" && this.isHuifu) {
          this.showWXPay = true;
          // if (localStorage.getItem('loginAccount') === "19168928480") {
          //   this.showWXPay = true;
          // }
        }

      }
    }

    // tslint:disable-next-line:max-line-length
    if (this.tagData.data.form !== undefined && this.tagData.data.form.data !== undefined && this.tagData.data.form.data.length > 0 && this.wxCode === 0 ) {
      this.payBack();
    }
  }

  getWXH5Code() {
    if  (this.vlaue === "1" && (this.userAgent.match(/micromessenger/i) !== null) && this.wxCode === 0) {
      this.isWXH5 = true;
      // 微信内置浏览器优先
      this.client = "JSAPI";
      const target: any = this.appGlobalService.getCurrentTarget();
      target.params['currentPath'] = localStorage.getItem('currentPath');
      let url = 'element/h5desk/h5wxRedirectUrl';
      if (this.appGlobalService.clientType === 'lj') {
       url = 'element/h5desk/h5wxfwRedirectUrl';
      }
      this.http.post(url, target,
      res => {
          console.log("h5RedirectUrl:" + res.redirectUrl);
          // alert(res.redirectUrl);
          // if (localStorage.getItem('loginAccount') === "19168928480") {
          //   alert(res.redirectUrl);
          // }
          window.location.href = res.redirectUrl;
      } , err => {
        console.log("h5RedirectUrl-err:" + err);
      });

      return true;
    } else {
      return false;
    }
  }
  async payBack() {
    const title =  this.tagData.data.form.title;
    const label =  this.tagData.data.form.data[0].label;
    if (this.tagData.data.form.data.length === 1 ) {
      const alert = await this.alert.create({
        message: title,
        buttons: [
            {
                text: label,
                handler: () => {
                  if (this.tagData.data.form.data[0].submit !== undefined) {
                    const submitData = this.tagData.data.form.data[0].submit;
                    this.submitData(submitData);
                  }
                  if (this.tagData.data.form.data[0].link !== undefined) {
                    const linkData = this.tagData.data.form.data[0].link;
                    this.gotoPage(linkData);
                  }
                }
            }
          ]
      });
      await alert.present();

    } else
    if (this.tagData.data.form.data.length === 2 ) {
      const alert = await this.alert.create({
        message: title,
        buttons: [
            {
                text: this.tagData.data.form.data[1].label,
                role: 'cancel',
                cssClass: 'secondary',
                handler: () => {
                  if (this.tagData.data.form.data[1].submit !== undefined) {
                    const submitData = this.tagData.data.form.data[1].submit;
                    this.submitData(submitData);

                  } else if (this.tagData.data.form.data[1].link !== undefined) {
                    const linkData = this.tagData.data.form.data[1].link;
                    // 支付遇到问题从新进入一次页面
                    this.appGlobalService.goBack(-3);
                    this.appGlobalService.popTarget();
                    this.appGlobalService.popTarget();
                    this.gotoPage(linkData);
                  }
            }
          },
            {
                text: label,
                cssClass: 'LJ',
                handler: () => {
                  if (this.tagData.data.form.data[0].submit !== undefined) {
                    const submitData = this.tagData.data.form.data[0].submit;
                    this.submitData(submitData);
                  }
                  if (this.tagData.data.form.data[0].link !== undefined) {
                    const linkData = this.tagData.data.form.data[0].link;
                    this.gotoPage(linkData);
                  }
                }
            }
          ]
      });
      await alert.present();
    }
  }

  submitData(submitData) {
    const param = {
      content: submitData.params,
      id: submitData.id,
      sessionId: localStorage.getItem('sessionId')
    };
    this.http.post('application/submit', param, res => {
      // 请求成功
      if (res.success) {
        console.log('submit success' + JSON.stringify(res));
        this.H5PayResPage(res);
      } else {
        // 请求数据失败
        this.H5PayResPage(res);
        this.appGlobalService.showToast(res.message, 2000, 'middle');
      }
    });
  }

  H5PayResPage(res) {
    this.gotoPage(res);
  }


  gotoPage(linkData) {
    if (linkData.type === 'page') {
       const pageParams = {
          pageId: linkData.target,
          params: linkData.params,
          sessionId: localStorage.getItem('sessionId')
        };
       this.appGlobalService.goToForward(pageParams);

    } else if (linkData.type === 'url') {
        this.appGlobalService.openUrl(this.tagData.data.detailContent.title, linkData.target);
    }
  }
  
  pay(btn) {
    const that = this;
    const userAgent = window.navigator.userAgent.toLowerCase();
    // 如果是APP 汇付支付 将submit请求转义到小程序
    // btn.submit.params.huifu = 'true'; // todo debug
    if (btn.submit.params.huifu && btn.submit.params.huifu === 'true') {

      if (this.client === 'APP') {
        if (this.vlaue === "1") {
          // 微信 走小程序
          that.huifuWXPay(btn, userAgent);
        } else {
          // 支付宝
          this.paySubmit(btn, userAgent);
        }
      } else if (this.client === 'JSAPI') {
        // wx小程序内
        this.paySubmit(btn, userAgent);
      } else if  (this.client === "BROWSER" ) {
        // wx 内浏览器
        if (this.vlaue === "1" && (userAgent.match(/micromessenger/i) !== null)) {
          this.paySubmit(btn, userAgent);

        } else {
          // 第三方浏览器 url -> 唤起小程序 同app支付:
          if (this.vlaue === "1") { // wx

            // that.showWXPay = false;
            // if (localStorage.getItem('loginAccount') === "19168928480") {
            that.showWXPay = true;
            this.paySubmit(btn, userAgent);


            // }
          } else { // ali
            this.paySubmit(btn, userAgent);
          }

        }
      }

    } else {
      // 原来的支付流程
      this.paySubmit(btn, userAgent);
    }

  }

  huifuWXPay(btn, userAgent) {
      const price = btn.submit.params.price;
      const v = parseFloat(price);
      if (isNaN(v)) {
        this.appGlobalService.showToast("系统繁忙请稍后再支付", 2000, "top");
        return;
      }

      const that = this;
      btn.submit.params['wxMini'] = 'fw';
      btn.submit.params.client = this.client;
      btn.submit.params.value = Number(this.vlaue);
      btn.submit.params.code = this.wxCode;
      const params0 = {
        id: btn.submit.id,
        content: btn.submit.params,
        sessionId: localStorage.getItem('sessionId')
        };
      Wechat.isInstalled(function (installed) {
        console.log("Wechat installed: " + (installed ? "Yes" : "No"));
        if (!installed) {
          this.appGlobalService.showToast("您没有安装微信", 2000, "top");
          return;
        }
        Wechat.sendPaymentRequest(params0, function(backAppParams) {
          console.log('汇付-小程序 Wechat pay resString backAppParams:', backAppParams);
          if (backAppParams.indexOf('paySuccess:false') > -1) {
            const errorMessage = (backAppParams.split(':false')[1]);
            // alert('支付失败!');
            console.log('pay failed');
            that.payFail(btn, errorMessage);
          } else if (backAppParams.indexOf('paySuccess:true') > -1) {
            const orderNo = (backAppParams.split(':true')[1]);
            console.log("paySuccess-->orderNo:" + orderNo);
            that.paySuccess(orderNo);
  
            // alert('支付成功!');
          } else if (backAppParams.indexOf('unablePay:') > -1) {
            console.log("unablePay:" + backAppParams);
            const p = backAppParams.split('unablePay:')[1];
            if (p === "submit req faile") {
              console.log('submit req faile');
            } else {
              that.payFail(btn, JSON.parse(p));
            }
          }
  
          }, function(reason) {
            console.log('汇付-小程序 Failed: ' + reason);
            // alert("汇付-小程序 Failed: " + reason);
          });

      }, function (reason) {
        this.appGlobalService.showToast("您没有安装微信", 2000, "top");

      });

  }
  paySubmit(btn, userAgent) {
    // 以下是原来的支付:
    if (localStorage.getItem('client') === "JSAPI") {
      // 小程序
      if (this.appGlobalService.clientType === 'ppw') {
        btn.submit.params['wxMini'] = 'ppw';
      } else if (this.appGlobalService.clientType === 'lj') {
        btn.submit.params['wxMini'] = 'fw';
        btn.submit.params.client = this.client;
      } else if (this.appGlobalService.clientType === 'js') {
        btn.submit.params['wxMini'] = 'fwsh';
        btn.submit.params.client = this.client;
      }
    } else {
      if  (this.vlaue === "1" && (userAgent.match(/micromessenger/i) !== null)) {
        btn.submit.params.H5WX = 1;
      }

      this.wxCode = this.appGlobalService.wxPayCode;
      // if (localStorage.getItem('loginAccount') === "19168928480") {
      //   alert("paySubmit wxCode:" + this.wxCode);
      // }
      if (this.getWXH5Code()) {
        return;
      }
    }

    if (this.vlaue >= 1 ) {
      console.log('支付方式------->', this.vlaue);
    } else {
      console.log('请选择支付方式------->!!!\n');
      this.appGlobalService.showToast('请选择支付方式', 1000, "top");
      return;
    }
    btn.submit.params.value = Number(this.vlaue);
    btn.submit.params.client = this.client;

    btn.submit.params.code = this.wxCode;
    const params = {
      id: btn.submit.id,
      content: btn.submit.params,
      sessionId: localStorage.getItem('sessionId')
    };
    // alert( "submit:" + JSON.stringify(params));
    this.http.post('application/submit', params, res => {
      // 请求成功
      if (res.success) {
        // 标记已绑定
        if ( res.openidError === false && this.isWXMIN) {
            localStorage.setItem(localStorage.getItem('sessionId'), "bindWeChatLoginCode");
        }
        console.log('可以支付 -->', res.message, JSON.stringify(res.data.payData));
        if (this.vlaue === '1') {
          if (localStorage.getItem('client') === "JSAPI") {
            // 小程序
            // wxec4de18f4a221e55
            const payData = JSON.parse(res.data.payData) ;
            // 汇付 && payData.data.resp_code === '20000000'
            // 汇付小程序的payData可以支付时候没有payData.data，跟汇付的支付宝不一样，汇付支付宝一直有payData.data这层数据
            if (payData.data && payData.data.resp_code  && payData.data.resp_desc) {
              this.appGlobalService.showToast(payData.data.resp_desc + "订单号：" + res.data.orderNo, 2000, "top");
              return;
            }

            const packageStr = payData.package.replace('=', '@');
            // tslint:disable-next-line:max-line-length
            const param = '?timestamp=' + payData.timeStamp + '&nonceStr=' + payData.nonceStr + '&package=' + packageStr + '&signType=' + payData.signType + '&paySign=' + payData.paySign + '&successParams=' + JSON.stringify(this.successParams(res.data.orderNo)) + '&failParams=' + JSON.stringify(this.failParams(btn, res, false)) ;
            // 定义path 与小程序的支付页面的路径相对应
            const path = '/pages/wxpay/wxpay' + param;
            // 通过JSSDK的api使小程序跳转到指定的小程序页面
            wx.miniProgram.navigateTo({url: path});
          } else
          // 微信内置浏览器优先
          if (userAgent.match(/micromessenger/i) !== null) {
            this.wxCode = 0;
            if (typeof WeixinJSBridge === 'undefined') {
              document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false);
            } else {
              // if (localStorage.getItem('loginAccount') === "19168928480") {
              //   alert( "wxh5payData:" + JSON.stringify(res.data.payData));
              // }

              const payData = JSON.parse(res.data.payData) ;
              this.payData = payData;
              this.onBridgeReady();
            }
          } else if (this.client === 'APP') {
            this.wechatPay(res.data.payData, res.data.orderNo);
          } else  if (this.client === 'BROWSER') {
            const payData: string = res.data.payData;
            console.log(payData);
            // 设置重定向地址为当前页面
            // const newPayData = payData.replace('return_url', localStorage.getItem("currentPath"));
            // console.log(encodeURI(newPayData) );
            if (res.data.eventResult) {
              if (res.data.eventResult === "P") { // 处理中
                if (this.retry < 3) {
                  this.checkedPayStatus();
                } else {
                  this.payFail(btn, { code: -1, message: "支付失败"} );
                }
              } else if (res.data.eventResult === "S") {
                this.paySuccess(this.orderNumber);
              } else if (res.data.eventResult === "F") {
                this.payFail(btn, { code: -1, message: "支付失败"} );
              } else {
                location.href = res.data.payData; // 发起支付
              }
            } else {
              location.href = res.data.payData; // 发起支付
            }
          }

        } else {
          if (this.client === 'APP') {
            this.orderNumber = res.data.orderNo;
            this.aliPay(res.data.payData, res.data.orderNo);

            if (btn.submit.params.huifu === 'true') {
              if (this.appGlobalService.eventService.eventEmit.listenerCount('checkPayStatus') > 0) {
                this.appGlobalService.eventService.eventEmit.removeListener('checkPayStatus');
              }
              const that = this;
              this.appGlobalService.eventService.eventEmit.on('checkPayStatus', e => {
                that.retry = 0;
                that.checkedPayStatus();
                that.appGlobalService.eventService.eventEmit.removeListener('checkPayStatus');
              });
            }


          } else {
            // 设置重定向地址为当前页面
            // const payData: string = res.data.payData;
            // const newPayData = payData.replace('return_url', localStorage.getItem("currentPath"));
            // console.log(encodeURI(newPayData));
            this.aliPayH5(res.data.payData, res.data.orderNo);
          }

        }
        // for debug
        // this.payFail(btn);
        // this.paySuccess('test123456');

      } else {
        // 请求数据失败
        if (res.message) {
          this.appGlobalService.showToast(res.message, 1500, "top");
        }
        console.log('不可支付 -->', res.message);
        this.payFail(btn, res);
      }
    }, err => {

    });
  }
  checkedPayStatus() {
    this.retry += 1;
    const btn = this.tagData.data.button;
    if (btn.checkSubmit) {
      setTimeout(() => {
        const params = {
          id: btn.checkSubmit.id,
          content: btn.checkSubmit.params,
          sessionId: localStorage.getItem('sessionId')
        };
  
        this.http.post('application/submit', params, res => {
          // 请求成功
          if (res.success && res.data && res.data.eventResult)  {
            console.log("查询支付结果：" + res.data.eventResult);
  
            if (res.data.eventResult === "P") { // 处理中
              if (this.retry < 3) {
                this.checkedPayStatus();
              } else {
                this.payFail(btn, { code: -1, message: "支付失败"} );
              }
            } else if (res.data.eventResult === "S") {
              this.paySuccess(this.orderNumber);
            } else if (res.data.eventResult === "F") {
              this.payFail(btn, { code: -1, message: "支付失败"} );
            }
          }
        } , err => {
  
        }
        );
  
      }, 500);
    }
    


  }
  failParams(btn, res, action?) {

    let params = {};
    if (btn.error.link.params) {
      // 支持后退的效果
      if (btn.error.link.params.back && btn.error.link.params.back === 'true') {
        if (localStorage.getItem('loginAccount') === "19168928480") {
          alert('fail will back last page');
        }
        // action 需要发生实际动作时候
        if (action) {
          if ( this.tagData.data.button.error.link.params.needRefresh === "true" ) {
            localStorage.setItem('needRefresh', 'true');
          }
          this.appGlobalService.popTarget();
          if (this.appGlobalService.wxPayCode !== 0) {
            if ( btn.error.link.params.wxInnerBeforeSubmitBack &&
              Number(btn.error.link.params.wxInnerBeforeSubmitBack) < 0  ) {
                history.go(Number(btn.error.link.params.wxInnerBeforeSubmitBack));
            } else {
              history.go(-2);
            }
            this.appGlobalService.wxPayCode = 0;
          } else if (this.userAgent.match(/micromessenger/i)) {
            if ( btn.error.link.params.wxInnerBack &&
              Number(btn.error.link.params.wxInnerBack) < 0  ) {
                history.go(Number(btn.error.link.params.wxInnerBack));
            } else {
              history.go(-2);
            }
  
          } else {
            this.appGlobalService.goBack();
          }
        }

      }

      btn.error.link.params.errorMessage = res.message;
      btn.error.link.params.errorCode = res.code;
      params = btn.error.link.params;
    } else {
      params = {
        errorMessage: res.message,
        errorCode: res.code
      };
    }
    const param = {
      params ,
      pageId: btn.error.link.target,
      sessionId: localStorage.getItem('sessionId')
    };
    param.params['replace'] = 'replace';
    return param;
  }
  payFail(btn, res) {
    const param = this.failParams(btn, res, true);
    if (param !== undefined) {
      this.appGlobalService.goToForward(param);
    }

  }

  // e.resultStatus  状态代码  e.result  本次操作返回的结果数据 e.memo 提示信息
  // e.resultStatus  9000  订单支付成功 ;8000 正在处理中  调用function success
  // e.resultStatus  4000  订单支付失败 ;6001  用户中途取消 ;6002 网络连接出错  调用function error
  // 当e.resultStatus为9000时，请去服务端验证支付结果
            /**
             * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
             * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
             * docType=1) 建议商户依赖异步通知
             */

  aliPay(payData, orderNo) {
    if (this.isHuifu) {
          const payDataObj = JSON.parse(payData);
          if (payDataObj.data && payDataObj.data.resp_code  && payDataObj.data.resp_desc && !payDataObj.data.qr_code) {
            if (payDataObj.data.resp_code === '20000000') {
              this.appGlobalService.showToast("查询支付状态", 1500, "top");
              this.checkedPayStatus();
            } else {
              this.appGlobalService.showToast(payDataObj.data.resp_desc + "订单号：" + orderNo, 2000, "top");
            }

          } else {
            cordova.plugins.alipay.payment(payData, (res) => {
              // 支付成功
              console.log("success", JSON.stringify(res));
              this.paySuccess(orderNo);
            }, (error) => {
              // 支付失败
              if (error.resultStatus === '-1') {
                this.appGlobalService.showToast("您没有安装支付宝", 2000, "top");
                // location.href = error.qrCode;
              }
              console.log("支付失败" + error.resultStatus);
            });
          }
    } else {

      cordova.plugins.alipay.payment(payData, (res) => {
        // 支付成功
        console.log("success", JSON.stringify(res));
        this.paySuccess(orderNo);

      }, (error) => {
        // 支付失败
        console.log("支付失败" + error.resultStatus);
      });
    }


  }
  aliPayH5(payData, orderNo) {
    if (this.isHuifu) {
        const payDataObj = JSON.parse(payData);
        // 汇付 && payDataObj.data.resp_code === '20000000'
        if (payDataObj.data && payDataObj.data.resp_code  && payDataObj.data.resp_desc) {
          if (payDataObj.data.qr_code) {
            //  汇付  "alipays://platformapi/startapp?saId=10000007&qrcode=" +
            location.href = payDataObj.data.qr_code;
            console.log(" aliPayH5 汇付");
          } else if (payDataObj.data.resp_code === '20000000') {
            this.appGlobalService.showToast("查询支付状态", 1500, "top");
            this.checkedPayStatus();
          } else {
            this.appGlobalService.showToast(payDataObj.data.resp_desc + "订单号：" + orderNo, 2000, "top");
          }
        }
    } else {
      location.href = 'https://openapi.alipay.com/gateway.do?' + payData;
      console.log(" aliPayH5");
    }

    // this.http.get('https://openapi.alipay.com/gateway.do?' + payData , res => {
    //   // alert(res);
    // });
  }
  wechatPay(payData, orderNo) {
    console.log('wechat pay info', JSON.parse(payData));
    const that = this;
    Wechat.isInstalled(function (installed) {
      console.log("Wechat installed: " + (installed ? "Yes" : "No"));
      if (!installed || installed === 0) { // 安卓wechat插件installed返回值 0,1
        this.appGlobalService.showToast("您没有安装微信", 2000, "top");
        return;
      }
      Wechat.sendPaymentRequest(JSON.parse(payData), function(success) {
        console.log('Wechat pay success', JSON.stringify(success));
        that.paySuccess(orderNo);
        }, function(reason) {
          alert("Failed: " + reason);
        });

  }, function (reason) {
    this.appGlobalService.showToast("您没有安装微信", 2000, "top");
  });
  }

  checkPayWay(item) {
    this.tagData.data.payWay.forEach((v) => {
      if (item === v) {
        if (!item.checked) {
          v.checked = true;
          this.vlaue = v.value;
        }
      } else {
        v.checked = false;
      }
    });
  }

  paySuccess(orderNumber) {
    this.appGlobalService.goToForward(this.successParams(orderNumber));
  }
  successParams(orderNumber) {
    let successParam: any;
    if (this.tagData.data.button.success.link.params) {
      successParam = this.tagData.data.button.success.link.params;
      successParam.payTime = this.appGlobalService.getNowFormatDate();
      successParam.orderNo = orderNumber;
    } else {
      successParam = {
        payTime: this.appGlobalService.getNowFormatDate(),
        orderNo: orderNumber
      };
    }
    const param = {
      params : successParam,
      pageId: this.tagData.data.button.success.link.target,
      sessionId: localStorage.getItem('sessionId')
    };
    param.params['replace'] = 'replace';

    return param;
  }

  async cancel() {
    const alert = await this.alert.create({
        message: '确定要放弃支付吗？',
        buttons: [
            {
                text: '取消',
                role: 'cancel',
                cssClass: 'secondary',
                handler: () => {
                    console.log('Confirm Cancel');
                }
            }, {
                text: '确定',
                cssClass: 'LJ',
                handler: () => {
                  if (this.tagData.data.button.success &&
                    this.tagData.data.button.success.link &&
                    this.tagData.data.button.success.link.params &&
                    this.tagData.data.button.success.link.params.canCancelPay
                  ) {
                    this.pageModalService.openPage(this.tagData.data.button.success.link);
                  } else {
                    console.log(history, 'histry');
                    this.debugShowCodeValue();
                    if ( this.tagData.data.button.submit.params.needRefresh === "true" ) {
                      localStorage.setItem('needRefresh', 'true');
                    }
                    this.appGlobalService.popTarget();
                    if (this.appGlobalService.wxPayCode !== 0) {
                      if ( this.tagData.data.button.submit.params.wxInnerBeforeSubmitBack &&
                        Number(this.tagData.data.button.submit.params.wxInnerBeforeSubmitBack) < 0  ) {
                          history.go(Number(this.tagData.data.button.submit.params.wxInnerBeforeSubmitBack));
                      } else {
                        history.go(-2);
                      }
                      this.appGlobalService.wxPayCode = 0;
                    } else if (this.userAgent.match(/micromessenger/i)) {
                      if ( this.tagData.data.button.submit.params.wxInnerBack &&
                        Number(this.tagData.data.button.submit.params.wxInnerBack) < 0  ) {
                          history.go(Number(this.tagData.data.button.submit.params.wxInnerBack));
                      } else {
                        history.go(-2);
                      }

                    } else if ( this.tagData.data.button.submit.params.back &&
                      Number(this.tagData.data.button.submit.params.back) < 0  ) {
                        history.go(Number(this.tagData.data.button.submit.params.back));
                    } else {
                      this.appGlobalService.goBack();
                    }
                  }
                }
            }
        ]
    });

    await alert.present();
}
debugShowCodeValue() {
  if (localStorage.getItem('loginAccount') === "19168928480") {
    alert('appGlobalService.wxPayCode = ' + this.appGlobalService.wxPayCode + 'wxcode = ' + this.wxCode );
  }
}
onBridgeReady() {
  if (this.payData) {
  // delete this.payData.prepay_id;
    const that = this;
    WeixinJSBridge.invoke(
      'getBrandWCPayRequest', this.payData,
      function(res) {
        // if (localStorage.getItem('loginAccount') === "19168928480") {
        //   alert( "支付结果：" + res.err_msg);
        // }
        that.appGlobalService.wxPayCode = 0;
        if (res.err_msg === 'get_brand_wcpay_request:ok') {
          // 使用以上方式判断前端返回,微信团队郑重提示：
          // res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          // console.log('支付成功');
          if (that.tagData.data.form !== undefined && that.tagData.data.form.data !== undefined && that.tagData.data.form.data.length > 0) {
            that.payBack();
          }
          // that.paySuccess(that.orderNumber);
          // alert('支付成功');

        } else
        if (res.err_msg === 'get_brand_wcpay_request:cancel') {
          console.log('支付取消');
        } else if (res.err_msg === 'get_brand_wcpay_request:fail') {
          console.log('支付失败');

        }
      });
  }
}

  // demoData() {
  //   this.tagData =  {
  //     data: {
  //       symbol: "¥",
  //       price: 2535,
  //       serviceName: "选址通会员",
  //       payWay: [{
  //           // checked: true,
  //           iconName: "pay_icon_wechat@3x.png",
  //           payName: "微信支付",
  //           info: "推荐安装维修7.0以上版本",
  //           value: 1 // value等于1，为微信支付
  //       }, {
  //         // checked: false,
  //           iconName: "pay_icon_alipay@3x.png",
  //           payName: "支付宝支付",
  //           info: "推荐有支付宝账户的用户使用",
  //           value: 2 // value等于2，为支付宝支付
  //       }],
  //       button: {
  //           label: "确认支付",
  //           submit: {

  //           },
  //           success: {
  //               link: {
  //                   type: "page",
  //                   target: "pageId",
  //                   params: {}
  //               }
  //           },
  //           error: {
  //               link: {
  //                   type: "page",
  //                   target: "pageId",
  //                   params: {}
  //               }
  //           }
  //         }
  //     }
  //   };
  // }
}
